using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.suppliers;


namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 根据ID获取供应商详细信息查询处理器
    /// </summary>
    public class GetSupplierByIdQueryHandler : IRequestHandler<GetSupplierByIdQuery, ApiResult<SupplierDetailDto>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetSupplierByIdQueryHandler> _logger;

        public GetSupplierByIdQueryHandler(
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<GetSupplierByIdQueryHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理根据ID获取供应商详细信息查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>供应商详细信息</returns>
        public async Task<ApiResult<SupplierDetailDto>> Handle(GetSupplierByIdQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询供应商详细信息，供应商ID: {SupplierId}", request.Id);

                // 根据ID查询供应商信息
                var supplier = await _supplierRepository.GetAll()
                    .Where(s => s.Id == request.Id && !s.IsDeleted)
                    .FirstOrDefaultAsync(cancellationToken);

                // 检查供应商是否存在
                if (supplier == null)
                {
                    _logger.LogWarning("未找到指定的供应商，供应商ID: {SupplierId}", request.Id);
                    
                    return new ApiResult<SupplierDetailDto>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到指定的供应商",
                        data = default
                    };
                }

                // 映射到DTO
                var supplierDetailDto = _mapper.Map<SupplierDetailDto>(supplier);

                _logger.LogInformation("成功查询供应商详细信息，供应商ID: {SupplierId}, 供应商名称: {SupplierName}", 
                    request.Id, supplier.SupplierName);

                return new ApiResult<SupplierDetailDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = supplierDetailDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询供应商详细信息时发生异常，供应商ID: {SupplierId}", request.Id);
                
                return new ApiResult<SupplierDetailDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询供应商详细信息时发生异常: {ex.Message}",
                    data = default
                };
            }
        }
    }
} 